package com.starblink.library.widget.product.pop

import android.app.Dialog
import android.content.Context
import android.graphics.Point
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.view.updateLayoutParams
import com.blankj.utilcode.util.BarUtils
import com.starblink.android.basic.BuildConfig
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.basic.ext.appScreenHeight
import com.starblink.basic.ext.load
import com.starblink.basic.ext.screenHeight
import com.starblink.basic.ext.screenWidth
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.databinding.PopFindSimilarGoodsBinding
import razerdp.basepopup.BasePopupWindow
import razerdp.util.log.PopupLog

/**
 *  Create by yuanl at 2023/3/29
 **/
class GoodsFindSimilarPop : BasePopupWindow {

    private val addClick: () -> Unit

    constructor(context: Context, addClick: () -> Unit) : super(context) {
        this.addClick = addClick
    }

    constructor(dialog: Dialog, addClick: () -> Unit) : super(dialog) {
        this.addClick = addClick
    }

    private val binding = PopFindSimilarGoodsBinding.inflate(LayoutInflater.from(context))

    private var drawable: Drawable? = null

    private val anchorRect = Rect(-1, -1, -1, -1)

    private val screenW = screenWidth

    private val halfScreenW = screenWidth.shr(1)

    private val anchorTagScreenH = screenHeight * (3.0 / 5.0)

    private var imgUrl: String? = null

    private var productId: String? = ""

    private var type: Int? = null

    var add = false
        set(value) {
            field = value
            binding.btnAdd.text =
                string(if (field) com.starblink.basic.style.R.string.added else com.starblink.basic.style.R.string.Add)
            binding.btnAdd.setCompoundDrawablesWithIntrinsicBounds(
                null,
                null,
                ContextCompat.getDrawable(
                    context,
                    if (field) com.starblink.basic.style.R.drawable.ic_svg_goods_added else com.starblink.basic.style.R.drawable.ic_svg_goods_add
                ),
                null
            )
        }

    init {
        contentView = binding.root
        PopupLog.setOpenLog(BuildConfig.DEBUG)
    }

    override fun onViewCreated(contentView: View) {
        super.onViewCreated(contentView)
        binding.img.enableCorner(16.dp2px())
        binding.btnFind.enableCorner(16.dp2px(), "top")
        binding.btnAdd.enableCorner(16.dp2px(), "bottom")

        //setBlurBackgroundEnable(true)

        /*setBlurOption(
            PopupBlurOption().setFullScreen(false).setBlurInDuration(-1L)
                .setBlurOutDuration(-1L)
                .setBlurRadius(10F)
                .setBlurView(context?.window?.decorView)
                .setBlurPreScaleRatio(0.25F)
                .setFullScreen(false)
        )*/
        setBackgroundColor(context.color(com.starblink.basic.style.R.color.clr_ad0f172a))

        binding.img.scaleType = ImageView.ScaleType.CENTER_INSIDE

        binding.btnFind.click {
            dismiss()

            if (imgUrl.isNullOrEmpty() || productId.isNullOrEmpty() || type == null) {
                return@click
            }

            CommonRoute.toFindSimilarGoods(imgUrl!!, productId!!, this@GoodsFindSimilarPop.type!!)
            /*navigationTo(RoutePage.ImageSearch.PAGE_FIND_SIMILAR) {
                extraOf(RoutePage.ImageSearch.ARGS_IMG_URL to imgUrl,
                    RoutePage.ARG.ID to productId,
                    RoutePage.ARG.TYPE to this@GoodsFindSimilarPop.type)
            }*/
        }
        binding.btnAdd.setOnClickListener {
            dismiss()
            addClick.invoke()
        }

        binding.root.setOnClickListener {
            dismiss()
        }


    }

    override fun onBeforeShow(): Boolean {
        val superVal = super.onBeforeShow()

        if (drawable != null) {
            binding.img.setImageDrawable(drawable)
        } else {
            binding.img.load(imgUrl)
        }


        val overWidth = anchorRect.width() * SCALE >= screenW

        if (anchorRect.left > -1 && anchorRect.top > -1) {
            (binding.img.layoutParams as ConstraintLayout.LayoutParams?)?.run {
                width = if (overWidth) anchorRect.width() else (anchorRect.width() * SCALE).toInt()
                height =
                    if (overWidth) anchorRect.height() else (anchorRect.height() * SCALE).toInt()
                if (overWidth) {
                    leftMargin = 0
                    rightMargin = 0

                    leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
                    rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
                } else {
                    leftMargin = 12.dp2px()
                    rightMargin = 12.dp2px()

                    if (anchorRect.left < halfScreenW) {
                        leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
                        rightToRight = ConstraintLayout.LayoutParams.UNSET
                    } else {
                        leftToLeft = ConstraintLayout.LayoutParams.UNSET
                        rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
                    }
                }
                if (anchorRect.bottom < anchorTagScreenH || anchorRect.top <= actionVHeight) {
                    topToBottom = ConstraintLayout.LayoutParams.UNSET
                    topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    bottomToBottom = ConstraintLayout.LayoutParams.UNSET
                } else {
                    topToBottom = binding.vBgAction.id
                    topToTop = ConstraintLayout.LayoutParams.UNSET
                    bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
                }
            }
            binding.vBgAction.updateLayoutParams<ConstraintLayout.LayoutParams> {
                if (overWidth) {
                    leftToLeft = binding.img.id
                    rightToRight = binding.img.id
                } else {
                    if (anchorRect.left < halfScreenW) {
                        leftToLeft = binding.img.id
                        rightToRight = ConstraintLayout.LayoutParams.UNSET
                    } else {
                        leftToLeft = ConstraintLayout.LayoutParams.UNSET
                        rightToRight = binding.img.id
                    }
                }
                if (anchorRect.bottom < anchorTagScreenH || anchorRect.top <= actionVHeight) {
                    topToBottom = binding.img.id
                    topToTop = ConstraintLayout.LayoutParams.UNSET
                    bottomToTop = ConstraintLayout.LayoutParams.UNSET
                } else {
                    topToBottom = ConstraintLayout.LayoutParams.UNSET
                    topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                    bottomToTop = binding.img.id
                }
            }
        }
        return superVal
    }

    private fun prepare(anchorView: View): Point {
        //anchorView.getGlobalVisibleRect(anchorRect)
        val array = intArrayOf(0, 0)
        anchorView.getLocationInWindow(array)
        anchorRect.set(
            array[0],
            array[1],
            array[0] + anchorView.measuredWidth,
            array[1] + anchorView.measuredHeight
        )
        drawable = (anchorView as? ImageView?)?.drawable

        val scaleH = if (anchorRect.width() * SCALE >= screenW) {
            anchorRect.height()
        } else (anchorRect.height() * SCALE).toInt()
        val point = Point(anchorRect.left, anchorRect.top - (scaleH - anchorRect.height()).shr(1))


        val contentEstimateH = actionVHeight + scaleH

        val bottomHeight = bottomHeight()
        if (anchorRect.top < 0) {
            point.y = 0
        } else if (anchorRect.bottom >= bottomHeight) {
            point.y = bottomHeight - contentEstimateH.toInt()
        } else if (anchorRect.bottom > anchorTagScreenH) {
            point.y = anchorRect.top - actionVHeight.toInt()
        }
        return point
    }

    private fun bottomHeight() = (context?.let {
        (screenHeight - (if (BarUtils.isNavBarVisible(it)) CommUtils.getBottomStatusHeight() else 0))
    } ?: appScreenHeight)

    private val actionVHeight: Float =
        (binding.vBgAction.layoutParams as ConstraintLayout.LayoutParams?)?.let {
            ((it.matchConstraintPercentWidth * screenW / (200.0f / 93.0f)) + it.topMargin + it.bottomMargin)
        } ?: 0F


    fun showPopup(anchorView: View, imgUrl: String, productId: String, type: Int, add: Boolean) {
        val p = prepare(anchorView)
        this.imgUrl = imgUrl
        this.productId = productId
        this.type = type
        this.add = add
        showPopupWindow(p.x, p.y)
    }

    /**
     * call after [showPopup]
     */
    fun track(page: Int, trackMap: Map<String, String>, traceInfo: String? = null) {
        binding.btnFind.trackData(
            element = SpmElementDef.POP_FIND_SIMILAR_CLICK,
            page = page,
            params = trackMap,
            traceInfo = traceInfo,
            onlyHit = true,
        )
        binding.btnAdd.trackData(
            element = SpmElementDef.POP_FIND_SIMILAR_ADD,
            page = page,
            params = mutableMapOf(
                "status" to (if (UserDataCenter.isLogin()) "1" else "0"),
                "result" to (if (this.add) "0" else "1"),
            ).apply {
                putAll(trackMap)
            },
            traceInfo = traceInfo,
            onlyHit = true,
        )
    }

    companion object {

        private const val SCALE = 1.2f

    }

}